<template>
  <div>
    <el-upload
      :class="hideUpload ? 'hide' : 'show'"
      :headers="{ WXToken: tokenStore().token, client: 'WEB_USER' }"
      v-model:file-list="fileList"
      :before-upload="beforeAvatarUpload"
      :limit="file_max"
      :on-change="changUpload"
      :on-success="handleAvatarSuccess"
      :show-file-list="true"
      action="/api/system/file/upload/webImage"
      list-type="picture-card"
    >
      <el-icon>
        <Plus />
      </el-icon>
      <template #file="{ file }">
        <div>
          <img :src="file.url" alt="" class="el-upload-list__item-thumbnail" />
          <span class="el-upload-list__item-actions">
            <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
              <el-icon><zoom-in /></el-icon>
            </span>
            <span class="el-upload-list__item-delete" @click="handleDownload(file)">
              <el-icon>
                <Download />
              </el-icon>
            </span>
            <span class="el-upload-list__item-delete" @click="handleRemove(file)">
              <el-icon>
                <Delete />
              </el-icon>
            </span>
          </span>
        </div>
      </template>
    </el-upload>
    <el-dialog v-model="dialogVisible">
      <img :src="dialogImageUrl" alt="Preview Image" w-full />
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'
import type { UploadFile, UploadFiles, UploadUserFile } from 'element-plus'
import { ElMessage } from 'element-plus/es'
import { tokenStore } from '@/store/token'

const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const fileList = ref<UploadUserFile[]>([])
const hideUpload = ref(false)
let props = defineProps({ file_url: { default: null }, file_max: { type: Number, default: 1 } })
const emit = defineEmits(['update:file_url', 'update:file_max'])
const fileType = ref(['png', 'jpg'])
// 删除文件
const handleRemove = (file: UploadFile) => {
  fileList.value = fileList.value?.filter(s => s.url != file.url) as UploadUserFile[]
  const allFile = fileList.value?.filter(s => s.url != file.url) as string[]
  if (props.file_max === 1) {
    if (allFile.length == 0) {
      emit('update:file_url', '')
    } else {
      emit('update:file_url', allFile[0])
    }
  } else {
    emit('update:file_url', allFile)
  }
  hideUpload.value = allFile.length === props.file_max
}

//上传成功
const handleAvatarSuccess = (response, uploadFile) => {
  uploadFile.url = response.data
}

//进页面加载图片
const loadData = () => {
  if (!props.file_url) {
    return
  }
  fileList.value = []
  //判断是否之穿一个
  if (props.file_max === 1) {
    const dir = props.file_url.split('/')
    fileList.value?.push({
      name: dir[dir.length - 1],
      url: props.file_url
    })
  } else {
    if (props.file_url) {
      const fileUrls = props.file_url
      if (fileUrls && fileUrls.length > 0) {
        fileUrls.forEach((ss: string) => {
          if (!ss) {
            return
          }
          const dir = ss.split('/')
          fileList.value?.push({
            name: dir[dir.length - 1],
            url: ss.valueOf()
          })
        })
      }
    }
  }
  hideUpload.value = fileList.value.length >= props.file_max
}

const changUpload = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  if (props.file_max == 1) {
    emit('update:file_url', uploadFiles[0].url)
  } else {
    emit(
      'update:file_url',
      uploadFiles.map(ss => ss.url)
    )
  }
  hideUpload.value = uploadFiles.length >= props.file_max
}

const beforeAvatarUpload = (file: any) => {
  if (file.type) {
    let fileExtension = ''
    if (file.name.lastIndexOf('.') > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)
    }
    const isTypeOk = fileType.value.some(type => {
      return fileExtension && fileExtension.indexOf(type) > -1
    })
    if (!isTypeOk) {
      ElMessage({
        message: '文件格式不正确，请上传' + fileType.value.join('/') + '格式文件！',
        type: 'error'
      })
      return false
    }
    if (file.size / 1024 / 1024 > 10) {
      ElMessage.error('图片大小不超过 10MB!')
      return false
    }
  } else {
    ElMessage({
      message: '文件格式不正确，请上传' + fileType.value.join('/') + '格式文件！',
      type: 'error'
    })
    return false
  }
  return true
}
const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url as any
  dialogVisible.value = true
}
const handleDownload = (file: UploadFile) => {
  const url = file.url
  fetch(url)
    .then(res => res.blob())
    .then(blob => {
      const elink = document.createElement('a')
      elink.download = file.name
      elink.style.display = 'none'
      elink.href = window.URL.createObjectURL(blob)
      document.body.appendChild(elink)
      elink.click()
      window.URL.revokeObjectURL(elink.href)
      document.body.removeChild(elink)
    })
}

// 加载图片
onMounted(async () => {
  loadData()
})
</script>
<style lang="scss" scoped>
.hide {
  position: relative;
  float: left;
  padding-top: 20px;
  padding-left: 23px;
  :deep(.el-upload--picture-card) {
    display: none;
    .el-upload-list__item {
      border: 0;
      border-radius: 0;
      margin: 0 30px 0 0;
    }
  }
}
</style>
